package com.pansoft.klinelib.util;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;

/**
 * Created by hou on 2015/8/14.
 */
public class DoubleUtil {

    public static double parseDouble(String parserDouble) {
        try {
            return Double.parseDouble(parserDouble);
        } catch (Exception e) {
            return 0;
        }
    }

    public static String format2Decimal(Double d) {
        NumberFormat instance = DecimalFormat.getInstance(Locale.US);
        instance.setMinimumFractionDigits(2);
        instance.setMaximumFractionDigits(2);
        return instance.format(d);
    }

    public static String formatDecimal(Double d) {
        NumberFormat instance = DecimalFormat.getInstance(Locale.US);
        instance.setMinimumFractionDigits(0);
        instance.setMaximumFractionDigits(8);
        return instance.format(d).replace(",", "");
    }


    /**
     * converting a double number to string by digits
     */
    public static String getStringByDigits(double num, int digits) {
       /* if (digits == 0) {
            return (int) num + "";
        } else {
            NumberFormat instance = DecimalFormat.getInstance();
            instance.setMinimumFractionDigits(digits);
            instance.setMaximumFractionDigits(digits);
            return instance.format(num).replace(",", "");
        }*/
        return String.format(Locale.US, "%." + digits + "f", num);
    }

    /**
     * 将数字转化为指定的长度
     *
     * @param number       数字
     * @param length       数字长度
     * @param minimumCount 小数最小位数
     * @return
     */
    public static String assignNumberFormat(double number, int length, int minimumCount) {
        NumberFormat numberFormat = new DecimalFormat("0.0000000000000000", DecimalFormatSymbols.getInstance(Locale.US));
        numberFormat.setRoundingMode(RoundingMode.FLOOR);
        //设置数值的小数部分允许的最小位数
        numberFormat.setMaximumFractionDigits(minimumCount);
        // 设置数值的小数部分允许的最小位数
        numberFormat.setMinimumFractionDigits(minimumCount);
        String formatString = numberFormat.format(number);
        if (length + 1 < formatString.length()) {
            formatString = formatString.substring(0, length + 1);
        }

        char var6 = formatString.charAt(formatString.length() - 1);
        String resultString = formatString;
        if (formatString.length() > 0) {
            if (var6 != '.') {
                resultString = formatString;
                if (var6 != ',') {
                    return resultString;
                }
            }
            resultString = formatString.substring(0, formatString.length() - 1);
        }

        return resultString;
    }
}
